<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="search">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/enterpriseAdd')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="parkList" @expand-change="click">
        <el-table-column type="expand">
          <template #default="{row}">
            <el-table :data="row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态">
                <template #default="scoped">
                  <el-tag>
                    {{ getStatus(scoped.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scoped">
                  <el-button size="mini" :disabled="!scoped.row.renewFlag" type="text">续租</el-button>
                  <el-button size="mini" :disabled="!scoped.row.exitFlag" type="text" @click="returnFn(scoped.row.id)">退租</el-button>
                  <el-button size="mini" type="text" @click="delFn(scoped.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="mini" type="text" @click="change(row)">添加合同</el-button>
            <el-button size="mini" type="text" @click="$router.push(`/contractDetail?id=${row.id}`)">查看</el-button>
            <el-button size="mini" type="text" @click="$router.push(`/enterpriseAdd?id=${row.id}`)">编辑</el-button>
            <el-button size="mini" type="text" @click="del(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        :current-page.sync="params.page"
        layout="total, prev, pager, next"
        :total="total"
        :page-size="params.pageSize"
        @current-change="getEnterpriseList"
      />
    </div>
    <!-- 添加合同弹窗 -->
    <el-dialog title="添加合同" :visible.sync="isShow" width="580px" @close="closeDialog">
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" size="mini" placeholder="请选择">
              <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              size="mini"
              @change="onChange"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload size="mini" action="#" :http-request="uploadRequest">
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="submit">确 定</el-button>
      </template>
    </el-dialog>
  </div>

</template>

<script>
import { getEnterpriseList, returnContract, deleteContract, getContractList, addContract, deleteEnterprise, getBuildingList, uploadAPI } from '@/api/park/ParkEnterprise'
export default ({
  name: 'Department',
  data() {
    return {
      params: {
        page: 1,
        pageSize: 5,
        name: ''
      },
      parkList: [],
      total: null,
      isShow: false, // 控制弹窗的显示与隐藏
      rentForm: {
        buildingId: '',
        rentTime: '',
        contractId: '',
        contractUrl: '',
        enterpriseId: null,
        type: 0
      },
      rentRules: {
        buildingId: [
          { required: true, message: '请选择租赁楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁起止日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传租赁合同', trigger: 'change' }
        ]
      },
      options: [], // 下拉框数据
      ContractList: {} // 合同列表
    }
  },
  created() {
    this.getEnterpriseList()
    this.getBuildingList()
  },
  methods: {
    // 获取企业列表
    async getEnterpriseList() {
      const { rows, total } = await getEnterpriseList(this.params)
      // this.parkList = rows
      this.parkList = rows.map((item) => {
        return {
          ...item,
          rentList: [] // 每一行补充存放合同的列表
        }
      })
      this.total = total
      // console.log(rows)
    },
    // 查询
    search() {
      this.params.page = 1
      this.getEnterpriseList()
    },
    // 删除
    async del(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteEnterprise(id)
        this.getEnterpriseList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 查询可租赁的楼宇
    async getBuildingList() {
      const data = await getBuildingList()
      this.options = data
    },
    // 选择日期
    onChange(value) {
      this.rentForm.rentTime = value
      this.rentForm = {
        ...this.rentForm,
        startTime: value[0],
        endTime: value[1]
      }
    },
    // 上传合同文件
    async uploadRequest(params) {
      const { file } = params
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 2)
      const { id, url } = await uploadAPI(formData)
      //   console.log(data)
      this.rentForm.contractId = id
      this.rentForm.contractUrl = url
    },
    // 添加合同 显示弹窗
    change(row) {
      this.rentForm.enterpriseId = row.id
      this.isShow = true
    },
    // 提交表单
    async submit() {
      if (!this.rentForm.enterpriseId) return
      await this.$refs['addForm'].validate()
      delete this.rentForm.rentTime
      // console.log(data)
      await addContract(this.rentForm)
      this.getEnterpriseList()
      this.closeDialog()
    },
    // 点击展开合同
    async click(row, rows) {
      // console.log(row, expandedRows)
      const isExpend = rows.find(item => item.id === row.id)
      if (isExpend) {
        const res = await getContractList(row.id)
        isExpend.rentList = res
        // console.log(res)
        console.log(row.rentList)
      }
    },
    // 判断合同状态
    getStatus(status) {
      switch (status) {
        case 0:
          return '待生效'
        case 1:
          return '生效中'
        case 2:
          return '已到期'
        default:
          return '已退租'
      }
    },
    // 删除合同
    delFn(id) {
      console.log(id)
      this.$confirm('此操作将永久删除该合同, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteContract(id)
        this.getEnterpriseList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },
    // 退租
    returnFn(id) {
      this.$confirm('确定要退租此合同吗?, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await returnContract(id)
        this.getEnterpriseList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },
    // 关闭弹窗 并重置表单
    closeDialog() {
      this.isShow = false
      this.$refs.addForm.resetFields()
    }
  }
})
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
